namespace Digitalmes.Utils;

/// <summary>
/// 字符串帮助类
/// </summary>
public static class StringUtils
{
    private static readonly Random Random = new();

    /// <summary>
    /// 随机字符串
    /// </summary>
    /// <param name="length">字符串长度</param>
    /// <returns></returns>
    public static string RandomString(int length = 10)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var content = new char[length];
        for (var i = 0; i < length; i++)
        {
            content[i] = chars[Random.Next(chars.Length)];
        }

        return new string(content);
    }

    /// <summary>
    /// 将字符串转换为long类型数组，如字符串 "1,2,3,4,5" 转换为数组 [1,2,3,4,5]。
    /// </summary>
    /// <param name="str">要转换的字符串</param>
    /// <returns></returns>
    /// <exception cref="FormatException"></exception>
    /// <exception cref="OverflowException"></exception>
    public static long[] String2LongArray(this string? str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return Array.Empty<long>();
        }

        var slist = str.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        return slist.Select(long.Parse).ToArray();
    }

    /// <summary>
    /// 首字母转小写
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string FirstCharToLower(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return s;

        var str = s.First().ToString().ToLower() + s[1..];
        return str;
    }

    /// <summary>
    /// 首字母大写
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string FirstCharToUpper(this string input)
    {
        if (string.IsNullOrEmpty(input))
            return input;

        string str = input.First().ToString().ToUpper() + input[1..];
        return str;
    }
}
